package HttpServer;

import Command.SetCommand;
import DB.FileCommand.aof;
import DB.FileCommand.rdb;
import DB.LogDb;
import Executor.DbThreadExecutor;
import Queue.CircleQueue;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class HttpServerClient {


    int port;
    public static  LogDb pureLogDb ;
    public static CircleQueue queue;
    public static aof aofCreater;
    public HttpServerClient(int port){
        this.port = port;
    }


    public void start( ReadHook readHook) throws Exception{
        // bootstrap为启动器
        ServerBootstrap bootstrap = new ServerBootstrap();
       // DbThreadExecutor.init();
        //接收 I/O 请求，并分配线程执行处理请求
        EventLoopGroup boos = new NioEventLoopGroup();
        EventLoopGroup work = new NioEventLoopGroup();
        bootstrap.group(boos,work)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .channel(NioServerSocketChannel.class) //使用NIO模式
                .childHandler(new HttpServerInitializer()); //初始化器为HttpServerInitializer

        readHook.hook();
        //todo 以后在CacheManager中做初始化
        pureLogDb = new LogDb("db.log");
        aofCreater = new aof("aof.log");
        queue = new CircleQueue();
        DbThreadExecutor.submitConsumer();

        ChannelFuture f = bootstrap.bind(new InetSocketAddress(port)).sync();

        System.out.println("server start port-"+port);
        f.channel().closeFuture().sync();

    }

    @FunctionalInterface
    public interface ReadHook {
        void hook();
    }

    @FunctionalInterface
    public interface ShutHook {
        void hook();
    }

}
